<?php

namespace App\Http\Services;

use App\Http\Model\AudioApi;
use App\Http\Model\Call;
use App\Http\Model\Config;
use App\Http\Model\Gift;
use App\Http\Model\GiftBag;
use App\Http\Model\User;
use App\Lib\Publisher;

class CallServices extends CommonServices
{
    private $config_model;
    private $gift_model;
    private $gift_bag_model;
    private $audio_model;
    private $call_model;
    private $user_model;
    private $call_id = 247;//打call id
    private $pay_call_num = 4; //需要数量
    private $liang_num = 321321;//靓号  和model保持一致
    private $redis_lock = 'SPEED:LOCK';
//    private $url = 'http://192.168.1.89:8081/#/call';//本地
//    private $url = 'http://47.103.212.118:5084/activity/index.html#/call';//测试  //跳转链接
    private $url = 'http://ztaudio-res.qianyancm.com/ztaudio-web/activity/index.html#/call';//正式
    private $mall_type = ['其他', '头饰', '座驾', '气泡', '名片', '主页飘'];//0：其他 1：头饰 2：座驾  3：气泡 4：名片
    private $speed_diamond = [0, 2, 2, 2, 4, 4, 8, 8, 16, 16, -1];//加速扣钻

    public function __construct()
    {
        $this->config_model = new Config();
        $this->gift_model = new Gift();
        $this->gift_bag_model = new GiftBag();
        $this->call_model = new  Call();
        $this->audio_model = new  AudioApi();
        $this->user_model = new  User();
    }

    public function getCallUserInfo($user_id)
    {
        $status = [
            'code' => 0,
            'msg' => '成功',
            'data' => []
        ];
        do {
            //查看用户打call信息
            $userCall = $this->call_model->getUserCall($user_id);
            $data['timestamp'] = -1;
            $data['award_log'] = [];
            if ($userCall) {
                $userCall = json_decode($userCall, true);
                $num = $userCall['num'];
                $diffTime = $userCall['timestamp'] - time();
                if ($diffTime <= 0) {
                    //到期开奖
                    $data['timestamp'] = -2;
                    $data['award_log'] = $this->speedAward($user_id, $num);
                } else {
                    $data['timestamp'] = $diffTime;
                }
            }
            //查看用户当日 加速次数
            $data['speed_num'] = $this->call_model->getSpeedNum($user_id) ?? 0;
            $data['speed_diamond'] = $this->speed_diamond[$data['speed_num']] ?? -1;
            //用户剩余打call数量
            $giftBag = $this->gift_bag_model->getGiftBag($user_id, $this->call_id);
            $callNUm = $giftBag['avail'] ?? 0;
            $data['callNumber'] = $giftBag['avail'] ?? 0;
            if ($callNUm >= 1000) {
                $callNUm = floor($callNUm / 1000) . 'k';
            }
            $data['callNum'] = $callNUm;
            //用户信息
            $userInfo = $this->user_model->getUserInfoByApi($user_id);
            $data['user_info'] = $userInfo;
            $status['data'] = $data;
        } while (false);
        return $status;
    }


    public function payCall($user_id, $num)
    {

        $status = [
            'code' => 0,
            'msg' => '参与成功，请等待开奖',
            'data' => []
        ];
        do {
            //查询用户打call数量
            $giftBag = $this->gift_bag_model->getGiftBag($user_id, $this->call_id);
            $callNum = $giftBag['avail'] ?? 0;
            $changeNum = $this->pay_call_num * $num;
            if ($callNum < $changeNum) {
                $res = $this->audio_model->getOpenRoomId();
                $room_ids = $res['data']['list'];
                $key = rand(0, count($room_ids) - 1);
                $room_id = $room_ids[$key] ?? 0;//随机跳转房间id
                $status = [
                    'code' => 3001,
                    'msg' => '您的打call数量不足,请去房间内获取打call',
                    'data' => ['room_id' => $room_id]
                ];
                break;
            }
            //查看是否合成中
            $userCall = $this->call_model->getUserCall($user_id);
            if ($userCall) {
                $status = [
                    'code' => 3002,
                    'msg' => '您已参会合成 请等待开奖',
                    'data' => []
                ];
                break;
            }
            //扣除打call
            $res = $this->audio_model->changeGiftBag($user_id, $this->call_id, $changeNum);
            if ($res['code'] != 0) {
                $status = [
                    'code' => $res['code'],
                    'msg' => $res['msg'],
                    'data' => []
                ];
                break;
            }
            //生成开奖缓存
            $data['timestamp'] = time() + 30;
            $data['num'] = $num;
            $this->call_model->setAwardList($user_id, json_encode($data));
        } while (false);
        return $status;
    }

    public function awardMall($user_id)
    {
        $status = [
            'code' => 0,
            'msg' => '成功',
            'data' => []
        ];
        do {
            $userCall = $this->call_model->getUserCall($user_id);
            if (!$userCall) {
                $status = [
                    'code' => 3002,
                    'msg' => '您暂未参与 请参与后开奖',
                    'data' => []
                ];
                break;
            }
            $data = json_decode($userCall, true);
            $num = $data['num'];
            $timestamp = $data['timestamp'];
            if ($timestamp > time()) {
                $status = [
                    'code' => 3002,
                    'msg' => '开奖时间未到',
                    'data' => []
                ];
                break;
            }
            $this->speedAward($user_id, $num);
        } while (false);
        return $status;
    }

    public function diamondSpeed($user_id)
    {
        $status = [
            'code' => 0,
            'msg' => '成功',
            'data' => []
        ];
        //加速开奖
        do {
            $lookKey = $this->redis_lock . $user_id;
            if (redis_lock($lookKey, 10) == false) {
                //校验任务
                $status = [
                    'code' => 3002,
                    'msg' => '操作太快啦~',
                    'data' => []
                ];
                break;
            }
            $userCall = $this->call_model->getUserCall($user_id);
            if (!$userCall) {
                $status = [
                    'code' => 3002,
                    'msg' => '您没有参与合成',
                    'data' => []
                ];
                break;
            }
            $data = json_decode($userCall, true);
            $num = $data['num'];
            $timestamp = $data['timestamp'];
            //查看用户当日加速次数
            $speedNum = $this->call_model->getSpeedNum($user_id) ?? 0;
            if ($speedNum >= 10) {
                $status = [
                    'code' => 3002,
                    'msg' => '加速次数上限，请明天再试',
                    'data' => []
                ];
                break;
            }
            if ($speedNum > 0) {
                $diamond = $this->speed_diamond[$speedNum];
                //扣除用户钻石
                $pay_res = $this->audio_model->diamond_recharge($user_id, $diamond, 8);
                if ($pay_res['code'] != 0) {
                    $status = [
                        'code' => $pay_res['code'],
                        'msg' => $pay_res['msg'],
                        'data' => [],
                    ];
                    break;
                }
            }
            $this->call_model->incSpeedNum($user_id);
            $status['data'] = $this->speedAward($user_id, $num);
            redis_unlock($lookKey);
        } while (false);
        return $status;
    }

    public function speedAward($user_id, $num)
    {
        do {
            $data = [];
            $numData = [];
            $userCall = $this->call_model->getUserCall($user_id);
            if (!$userCall) {
                break;
            }
            $pondLevel = 0;
            if ($num >= 10) {
                $pondLevel = 1;
            }
            if ($pondLevel == 1 && time() >= 1614528000) { // 几天后可出靓号
                $pondLevel = 2;//走靓号奖池
            }
            //查看是否生成三个奖池
            $existsPond = $this->call_model->existsPond();
            if (!$existsPond) {
                $this->call_model->createPond(2);
                $this->call_model->createPondExists();
            }
            while ($num > 0) {
                $pondId = $this->call_model->getPond($pondLevel);
//                $pondId = 279;//测试数据
                if (is_null($pondId)) {
                    //当前靓号奖池为空
                    if ($pondLevel == 2) {
                        $pondLevel = 1;//靓号奖池抽完 转为 普通大奖池
                        $pondId = $this->call_model->getPond($pondLevel);
                        if (is_null($pondId)) {//普通奖池为空
                            $this->call_model->createPond($pondLevel);
                            $pondId = $this->call_model->getPond($pondLevel);
                        }
                    } else {
                        $this->call_model->createPond($pondLevel);
                        $pondId = $this->call_model->getPond($pondLevel);
                    }
                }
                if ($pondId == $this->liang_num) {
                    $user_info = $this->user_model->getUserInfoByApi($user_id);
                    //靓号
                    $setStatus = $this->call_model->setNumberToUser($user_info);
                    if ($setStatus == 1) {
                        //飘屏
                        $msg = '恭喜' . $user_info['nickname'] . '在合成打call活动中获得靓号' . $pondId . ',请尽快联系客服领取';
                        $this->audio_model->sendAllAppApi($user_id, 0, $msg);
                        //系统消息
                        $msg = '您在打call活动中获得靓号' . $this->liang_num . '，请尽快联系客服领取~';
                        $this->audio_model->sendMsgApi($user_id, $msg);
                        //纪录
                        $this->call_model->createAwardLog($user_id, '靓号' . $pondId, 1);
                        $numData[$num]['name'] = '靓号' . $pondId;
                        $numData[$num]['img'] = 'http://ztaudio-res.qianyancm.com/icon/liang.png';
                    }
                } else {
                    //赠送道具
                    $this->audio_model->sendAllProp($user_id, $pondId, 2, 1, 10);
                    //生成记录
                    $mallInfo = $this->gift_model->getMallInfoCache($pondId);
                    $mallName = $mallInfo['goods_name'] . $this->mall_type[$mallInfo['goods_type']];
                    $this->call_model->createAwardLog($user_id, $mallName, 0);
                    $data[$num]['name'] = $mallInfo['goods_name'];
                    $data[$num]['img'] = $mallInfo['small_img'];

//                    if (in_array($mallInfo['goods_type'], [1, 3, 4])) {
//                        $data[$num]['img'] = $mallInfo['small_img'];
//                    } else {
//                        $data[$num]['img'] = $mallInfo['small_img'];
//                    }
                }
                $num--;
            }
            //删除用户参与信息
            $this->call_model->delUserCall($user_id);
            //删除用户发送信息
            $this->call_model->delMsgLog($user_id);
        } while (false);
        return array_merge($numData, $data);
    }

    //获取可开奖用户发送消息
    public function getUserSendMsg()
    {

        $userCall = $this->call_model->getUserCallAll();
        if (empty($userCall)) {
            return true;
        }
        foreach ($userCall as $user_id => $v) {
            $data = json_decode($v, true);
            $timestamp = $data['timestamp'];
            //用户单次发送
            $log = $this->call_model->msgLog($user_id);
            if (!$log) {
                continue;
            }
            if ($timestamp < time()) {
                //发送消息
                $this->audio_model->sendMsgApiUrl($user_id, '您的奖励正在合成中,记得回到活动页面领取奖励哦!', $this->url . '?user_id=' . $user_id, '');
            }
        }
        return true;
    }


    //查看中奖纪录
    public function getLog($user_id)
    {
        $log = $this->call_model->getAwardLog($user_id);
        $log = array_reverse($log);
        $i = 0;
        $data = [];
        foreach ($log as $k => $v) {
            $key = explode('-', $k);
            $data[$i] = [
                'name' => $key[0],
                'date' => date('m' . '月' . 'd' . '日', $key[1]),
                'type' => $v,
            ];
            $i++;
        }
        return $data;
    }

}
